﻿using System.IO;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MongoDB.Driver.GridFS;

namespace MongoScienceDAL.Core.Tests
{
    public class MongoGridFsTestBase
    {
        public static Stream GetStream(string value)
        {
            var encoding = new UTF8Encoding();
            var data = encoding.GetBytes(value);
            var memoryStream = new MemoryStream(data);
            return memoryStream;
        }

        public static string ReadStream(Stream stream)
        {
            var streamReader = new StreamReader(stream);
            return streamReader.ReadToEnd();
        }

        public void CleanupAllFiles()
        {
            var database = TestHarness.DataSource.Database;
            var files = database.GridFS.Files;

            foreach (var file in files.FindAll())
            {
                database.GridFS.DeleteById(file["_id"]);
            }
        }

        public MongoGridFS GetGridFSReference()
        {
            return TestHarness.DataSource.Database.GridFS;
        }

        public ScienceFileRepository GetFileRepository()
        {
            var dataSource = TestHarness.DataSource;
            return new ScienceFileRepository(dataSource);
        }

        public ScienceVersionedFileRepository GetVersionedFileRepository()
        {
            var dataSource = TestHarness.DataSource;
            return new ScienceVersionedFileRepository(dataSource);
        }

        [TestMethod]
        public void GetStreamAndReadStreamShouldConvertToAndFromStreamsCorrectly()
        {
            const string testValue = "This is a test stream that will help us learn about others and ourselves.";

            var stream = GetStream(testValue);
            var result = ReadStream(stream);

            Assert.AreEqual(result, testValue);
        }

        [TestMethod]
        public void CleanupAllFilesDeletesFilesCorrectly()
        {
            var dataSource = TestHarness.DataSource;

            Assert.AreEqual(0,dataSource.Database.GridFS.Files.Count());

            dataSource.Database.GridFS.Upload(GetStream("test123"), "test123");
            dataSource.Database.GridFS.Upload(GetStream("test231"), "test231");
            dataSource.Database.GridFS.Upload(GetStream("test312"), "test312");

            Assert.AreEqual(3, dataSource.Database.GridFS.Files.Count());

            CleanupAllFiles();

            Assert.AreEqual(0, dataSource.Database.GridFS.Files.Count());
        }
    }
}
